import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { HotItemBase, Platform, TimeRange } from '../types/hotRadar';
import { message } from 'antd';

interface HotRadarFilters {
  platforms: Platform[];
  timeRange: TimeRange | { start: string; end: string };
  category?: string;
  keyword?: string;
  sortBy?: 'heat' | 'time' | 'rank';
  sortOrder?: 'asc' | 'desc';
  showFavoritesOnly?: boolean;
}

interface HotRadarState {
  // Hot items data
  hotItems: HotItemBase[];
  currentPage: number;
  pageSize: number;
  total: number;
  
  // Filters
  filters: HotRadarFilters;
  
  // Favorites
  favoriteIds: string[];
  
  // WebSocket connection
  wsConnection: WebSocket | null;
  isConnected: boolean;
  
  // Actions
  setHotItems: (items: HotItemBase[]) => void;
  setCurrentPage: (page: number) => void;
  setPageSize: (size: number) => void;
  setTotal: (total: number) => void;
  setFilters: (filters: HotRadarFilters) => void;
  resetFilters: () => void;
  
  // Favorite actions
  toggleFavorite: (itemId: string) => void;
  setFavoriteIds: (ids: string[]) => void;
  
  // WebSocket actions
  connectWebSocket: () => void;
  disconnectWebSocket: () => void;
  handleWebSocketMessage: (message: any) => void;
}

const defaultFilters: HotRadarFilters = {
  platforms: [],
  timeRange: TimeRange.TODAY,
  sortBy: 'heat',
  sortOrder: 'desc',
  showFavoritesOnly: false,
};

export const useHotRadarStore = create<HotRadarState>()(
  devtools(
    persist(
      (set, get) => ({
        // Initial state
        hotItems: [],
        currentPage: 1,
        pageSize: 20,
        total: 0,
        filters: defaultFilters,
        favoriteIds: [],
        wsConnection: null,
        isConnected: false,

        // Actions
        setHotItems: (items) => set({ hotItems: items }),
        setCurrentPage: (page) => set({ currentPage: page }),
        setPageSize: (size) => set({ pageSize: size, currentPage: 1 }),
        setTotal: (total) => set({ total }),
        setFilters: (filters) => set({ filters, currentPage: 1 }),
        resetFilters: () => set({ filters: defaultFilters, currentPage: 1 }),

        // Favorite actions
        toggleFavorite: (itemId) => {
          const { favoriteIds } = get();
          const newFavoriteIds = favoriteIds.includes(itemId)
            ? favoriteIds.filter(id => id !== itemId)
            : [...favoriteIds, itemId];
          
          set({ favoriteIds: newFavoriteIds });
          
          // Show feedback message
          if (newFavoriteIds.includes(itemId)) {
            message.success('已添加到收藏');
          } else {
            message.info('已取消收藏');
          }
        },
        
        setFavoriteIds: (ids) => set({ favoriteIds: ids }),

        // WebSocket actions
        connectWebSocket: () => {
          const wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:8002';
          const ws = new WebSocket(`${wsUrl}/ws/hot-items`);
          
          ws.onopen = () => {
            console.log('WebSocket connected');
            set({ wsConnection: ws, isConnected: true });
            message.success('实时更新已连接');
          };

          ws.onmessage = (event) => {
            try {
              const data = JSON.parse(event.data);
              get().handleWebSocketMessage(data);
            } catch (error) {
              console.error('Failed to parse WebSocket message:', error);
            }
          };

          ws.onerror = (error) => {
            console.error('WebSocket error:', error);
            message.error('实时更新连接失败');
          };

          ws.onclose = () => {
            console.log('WebSocket disconnected');
            set({ wsConnection: null, isConnected: false });
            
            // Attempt to reconnect after 5 seconds
            setTimeout(() => {
              if (!get().isConnected) {
                get().connectWebSocket();
              }
            }, 5000);
          };
        },

        disconnectWebSocket: () => {
          const { wsConnection } = get();
          if (wsConnection) {
            wsConnection.close();
            set({ wsConnection: null, isConnected: false });
          }
        },

        handleWebSocketMessage: (message) => {
          const { hotItems } = get();
          
          switch (message.type) {
            case 'new_item':
              // Add new item to the top of the list
              set({ hotItems: [message.data, ...hotItems] });
              message.info('发现新的热点内容');
              break;
              
            case 'update_item':
              // Update existing item
              const updatedItems = hotItems.map(item =>
                item.item_id === message.data.item_id ? message.data : item
              );
              set({ hotItems: updatedItems });
              break;
              
            case 'remove_item':
              // Remove item from list
              const filteredItems = hotItems.filter(
                item => item.item_id !== message.data.item_id
              );
              set({ hotItems: filteredItems });
              break;
              
            case 'batch_update':
              // Replace entire list with new data
              set({ hotItems: message.data });
              message.success('热点数据已更新');
              break;
              
            default:
              console.log('Unknown WebSocket message type:', message.type);
          }
        },
      }),
      {
        name: 'hot-radar-store',
        partialize: (state) => ({
          favoriteIds: state.favoriteIds,
          filters: state.filters,
          pageSize: state.pageSize,
        }),
      }
    )
  )
);